<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>北京旅游地图</title>
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=gfXEYso6gF84SwIw29zwwFDyxWOrWMzy&type=webgl&services=&callback=initialize"></script>
    <style type="text/css">
        body, html {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
        }
        #map-container {
            width: 100%;
            height: 100%;
            position: relative;
        }
        #map {
            width: 100%;
            height: 100%;
        }
        #place-types {
            position: absolute;
            top: 10px;
            left: 10px;
            background: white;
            border-radius: 5px;
            padding: 10px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            z-index: 1000;
        }
        #place-types label {
            display: block;
            margin: 5px 0;
        }
        .control-panel {
            position: absolute;
            top: 10px;
            right: 10px;
            background: white;
            border-radius: 5px;
            padding: 10px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            width: 250px;
            max-height: 90vh;
            overflow-y: auto;
        }
        /* 返回按钮样式 */
        .back-button {
            width: 100%;
            padding: 8px;
            background: #f44336;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            margin-bottom: 10px;
            font-weight: bold;
            font-size: 14px;
        }
        .back-button:hover {
            background: #d32f2f;
        }
        .info-window {
            max-width: 300px;
        }
        .info-window h3 {
            margin: 5px 0;
            color: #d00;
        }
        .info-window p {
            margin: 5px 0;
        }
        .info-window button {
            margin-top: 10px;
            padding: 5px 10px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        .info-window button:hover {
            background: #0056b3;
        }
        #search-box {
            width: 100%;
            padding: 8px;
            margin-bottom: 10px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
        #route-panel {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }
        #route-panel button {
            width: 100%;
            padding: 8px;
            background: #28a745;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            margin-top: 10px;
        }
        #route-panel button:hover {
            background: #218838;
        }
        #recommendations-panel {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
            max-height: 40vh;
            overflow-y: auto;
        }
        #recommendations-panel h3 {
            color: #d00;
            margin-bottom: 10px;
        }
        #recommended-places li {
            transition: all 0.3s ease;
            margin-bottom: 8px;
            padding: 8px;
            border-radius: 4px;
            background-color: #f9f9f9;
            border-left: 4px solid #28a745;
        }
        #recommended-places li:hover {
            background-color: #f0f0f0 !important;
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .rating-stars {
            color: gold;
            font-size: 18px;
        }
        .sort-control {
            margin: 10px 0;
            display: flex;
            align-items: center;
        }
        .sort-control label {
            margin-right: 8px;
        }
        .sort-control select {
            flex: 1;
            padding: 5px;
            border-radius: 3px;
            border: 1px solid #ccc;
        }
        .search-button {
            padding: 5px 10px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            margin-left: 5px;
        }
        .search-button:hover {
            background: #0056b3;
        }
        /* 推荐地点计数标记 */
        .recommendation-count {
            display: inline-block;
            width: 20px;
            height: 20px;
            background-color: #28a745;
            color: white;
            border-radius: 50%;
            text-align: center;
            line-height: 20px;
            margin-right: 8px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div id="map-container">
        <div id="map"></div>
        
        <div id="place-types">
            <h3>地点类型</h3>
            <label><input type="checkbox" value="all" checked> 全部</label>
            <label><input type="checkbox" value="景点"> 景点</label>
            <label><input type="checkbox" value="学校"> 学校</label>
            <label><input type="checkbox" value="餐厅"> 餐厅</label>
            <label><input type="checkbox" value="商店"> 商店</label>
            <label><input type="checkbox" value="图书馆"> 图书馆</label>
            <label><input type="checkbox" value="交通"> 交通</label>
            <label><input type="checkbox" value="医院"> 医院</label>
            <label><input type="checkbox" value="购物"> 购物</label>
        </div>
        
        <div class="control-panel">
            <!-- 返回按钮直接显示在顶部 -->
            <a href="/" style="display:block; background:#f44336; color:white; text-align:center; padding:10px; margin-bottom:15px; text-decoration:none; font-weight:bold; border-radius:4px;">返回首页</a>
            
            <h3>地点搜索</h3>
            <input type="text" id="search-box" placeholder="输入地点名称或关键词">
            <div class="sort-control">
                <label>排序方式：</label>
                <select id="search-sort">
                    <option value="relevance">相关性</option>
                    <option value="popularity">热度</option>
                    <option value="rating">评价</option>
                </select>
                <button class="search-button" onclick="searchPlaces(document.getElementById('search-box').value)">搜索</button>
            </div>
            <div id="search-results"></div>
            
            <div id="recommendations-panel">
                <h3 style="color:#d00; margin-top:15px; border-top:1px solid #eee; padding-top:15px;">景点与学校推荐</h3>
                <div class="sort-control">
                    <label>推荐方式：</label>
                    <select id="recommend-sort" onchange="loadRecommendedPlaces()">
                        <option value="popularity">按热度排序</option>
                        <option value="rating">按评价排序</option>
                    </select>
                </div>
                <div id="recommended-places">
                    <!-- 默认显示一些静态内容，确保即使JavaScript未加载也能看到内容 -->
                    <ul style="list-style: none; padding: 0; margin: 0;">
                        <li style="padding: 8px; margin-bottom: 5px; border-bottom: 1px solid #eee; cursor: pointer; background-color: #f9f9f9; border-left: 4px solid #28a745;">
                            <span style="display: inline-block; width: 20px; height: 20px; background-color: #28a745; color: white; border-radius: 50%; text-align: center; line-height: 20px; margin-right: 8px; font-weight: bold;">1</span>
                            <strong>故宫博物院</strong> <small>(景点)</small><br>
                            <span><strong>热度:</strong> 96.6</span>
                        </li>
                        <li style="padding: 8px; margin-bottom: 5px; border-bottom: 1px solid #eee; cursor: pointer; background-color: #f9f9f9; border-left: 4px solid #28a745;">
                            <span style="display: inline-block; width: 20px; height: 20px; background-color: #28a745; color: white; border-radius: 50%; text-align: center; line-height: 20px; margin-right: 8px; font-weight: bold;">2</span>
                            <strong>清华大学</strong> <small>(学校)</small><br>
                            <span><strong>热度:</strong> 84.5</span>
                        </li>
                    </ul>
                </div>
            </div>
            
            <div id="route-panel">
                <h3>路线规划</h3>
                <div id="start-point">起点: <span>未选择</span></div>
                <div id="end-point">终点: <span>未选择</span></div>
                <button id="plan-route" disabled>规划路线</button>
                <div>
                    <label><input type="radio" name="route-type" value="driving" checked> 驾车</label>
                    <label><input type="radio" name="route-type" value="walking"> 步行</label>
                </div>
            </div>
        </div>
    </div>
    
    <script type="text/javascript">
        // 全局变量
        var map;                   // 地图实例
        var markers = [];          // 地点标记集合
        var placeOutlines = [];    // 地点轮廓集合
        var internalMarkers = [];  // 内部地点标记集合
        var selectedPlaces = [];   // 已选择的地点
        var startPoint = null;     // 路线起点
        var endPoint = null;       // 路线终点
        var routeLine = null;      // 当前路线
        
        // 百度地图API加载完成后的回调函数
        function initialize() {
            // 地图初始化
            initMap();
        }
        
        // 地图初始化
        function initMap() {
            // 创建地图实例
            map = new BMap.Map("map");
            
            // 设置地图中心点为北京市中心，缩放级别为12
            var beijingCenter = new BMap.Point(116.317547, 39.99887);
            map.centerAndZoom(beijingCenter, 12);
            
            // 启用鼠标滚轮缩放
            map.enableScrollWheelZoom(true);
            
            // 添加地图控件
            map.addControl(new BMap.NavigationControl());     // 导航控件
            map.addControl(new BMap.ScaleControl());          // 比例尺控件
            map.addControl(new BMap.OverviewMapControl());    // 缩略图控件
            map.addControl(new BMap.MapTypeControl());        // 地图类型控件
            
            // 百度地图API密钥权限提示
            console.log("注意：路线规划功能需要单独申请开通，请确保API密钥有足够的权限。" +
                       "如果遇到'APP服务被禁用'错误，请前往百度地图开放平台(https://lbsyun.baidu.com/)申请新的密钥，" +
                       "并确保开通了路线规划服务权限。");
            
            // 显示北京市边界
            function showBeijingBoundary() {
                var bdary = new BMap.Boundary();
                bdary.get("北京市", function(rs) {
                    var count = rs.boundaries.length;
                    if (count === 0) {
                        console.error('未能获取北京市边界');
                        return;
                    }
                    
                    for (var i = 0; i < count; i++) {
                        var ply = new BMap.Polygon(rs.boundaries[i], {
                            strokeWeight: 2,
                            strokeColor: "#ff6600",
                            fillColor: "",
                            fillOpacity: 0.2
                        });
                        map.addOverlay(ply);
                    }
                });
            }
            
            // 加载地点数据
            function loadPlaces() {
                console.log("正在加载地点数据...");
                fetch('/api/places')
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('网络请求失败: ' + response.status);
                        }
                        return response.json();
                    })
                    .then(places => {
                        console.log(`成功加载 ${places.length} 个地点`);
                        places.forEach(place => {
                            addPlaceMarker(place);
                        });
                        
                        // 初始化筛选器事件
                        initFilterEvents();
                        
                        // 调整地图视图以包含所有标记
                        if (markers.length > 0) {
                            var points = markers.map(marker => marker.getPosition());
                            map.setViewport(points);
                        }
                    })
                    .catch(error => {
                        console.error('加载地点数据失败:', error);
                        alert('加载地点数据失败，请检查服务器连接');
                    });
            }
            
            // 根据地点类型获取不同图标
            function getIconByType(type) {
                var iconUrl = '';
                var iconSize = new BMap.Size(24, 24);
                
                switch(type) {
                    case '景点':
                        iconUrl = 'https://api.map.baidu.com/images/marker_red.png';
                        break;
                    case '学校':
                        iconUrl = 'https://api.map.baidu.com/images/marker_blue.png';
                        break;
                    case '餐厅':
                        iconUrl = 'https://api.map.baidu.com/images/marker_yellow.png';
                        break;
                    default:
                        iconUrl = 'https://api.map.baidu.com/images/marker_green.png';
                }
                
                return new BMap.Icon(iconUrl, iconSize);
            }
            
            // 添加地点标记
            function addPlaceMarker(place) {
                var point = new BMap.Point(place.longitude, place.latitude);
                var marker = new BMap.Marker(point, {
                    icon: getIconByType(place.type)
                });
                
                // 设置标记的自定义属性
                marker.placeId = place.id;
                marker.placeName = place.name;
                marker.placeType = place.type;
                
                // 添加到地图
                map.addOverlay(marker);
                markers.push(marker);
                
                // 如果有轮廓数据，添加轮廓
                if (place.outline && place.outline !== "") {
                    try {
                        var outlineData = JSON.parse(place.outline);
                        // 如果轮廓数据有效，添加多边形
                        if (outlineData && outlineData.results && outlineData.results.length > 0) {
                            var result = outlineData.results[0];
                            if (result.geo && result.geo.length > 0) {
                                var points = [];
                                var coords = result.geo[0].coordinates[0];
                                
                                for (var i = 0; i < coords.length; i++) {
                                    var lng = coords[i][0];
                                    var lat = coords[i][1];
                                    points.push(new BMap.Point(lng, lat));
                                }
                                
                                if (points.length > 2) {
                                    var polygon = new BMap.Polygon(points, {
                                        strokeColor: "#ff0000",
                                        strokeWeight: 2,
                                        strokeOpacity: 0.5,
                                        fillColor: getColorByType(place.type),
                                        fillOpacity: 0.2
                                    });
                                    
                                    // 设置轮廓的自定义属性
                                    polygon.placeId = place.id;
                                    polygon.placeType = place.type;
                                    
                                    map.addOverlay(polygon);
                                    placeOutlines.push(polygon);
                                }
                            }
                        }
                    } catch (e) {
                        console.error('解析轮廓数据失败:', e, place);
                    }
                }
            }
            
            // 根据地点类型获取颜色
            function getColorByType(type) {
                switch(type) {
                    case '景点': return "#ff5555";
                    case '学校': return "#5555ff";
                    case '餐厅': return "#ffaa55";
                    case '商店': return "#55ff55";
                    case '图书馆': return "#aa55ff";
                    case '交通': return "#ffff55";
                    case '医院': return "#ff55aa";
                    case '购物': return "#55ffaa";
                    default: return "#aaaaaa";
                }
            }
            
            // 生成评分星星
            function getRatingStars(rating) {
                if (rating === 0) return '暂无评分';
                
                // 计算整星数和半星数
                const fullStars = Math.floor(rating);
                const halfStar = rating - fullStars >= 0.5 ? 1 : 0;
                const emptyStars = 5 - fullStars - halfStar;
                
                let stars = '';
                // 添加整星
                for (let i = 0; i < fullStars; i++) {
                    stars += '★';
                }
                // 添加半星
                if (halfStar) {
                    stars += '☆';
                }
                // 添加空星
                for (let i = 0; i < emptyStars; i++) {
                    stars += '☆';
                }
                
                return stars;
            }
            
            // 设置为路线起点
            function setAsStart(placeId, placeName) {
                var place = markers.find(m => m.placeId === placeId);
                if (place) {
                    startPoint = {
                        id: placeId,
                        name: placeName,
                        lat: place.getPosition().lat,
                        lng: place.getPosition().lng
                    };
                    document.querySelector('#start-point span').textContent = placeName;
                    updateRoutePlanButton();
                }
            }
            
            // 设置为路线终点
            function setAsEnd(placeId, placeName) {
                var place = markers.find(m => m.placeId === placeId);
                if (place) {
                    endPoint = {
                        id: placeId,
                        name: placeName,
                        lat: place.getPosition().lat,
                        lng: place.getPosition().lng
                    };
                    document.querySelector('#end-point span').textContent = placeName;
                    updateRoutePlanButton();
                }
            }
            
            // 更新路线规划按钮状态
            function updateRoutePlanButton() {
                var button = document.getElementById('plan-route');
                button.disabled = !(startPoint && endPoint);
                
                if (startPoint && endPoint) {
                    button.addEventListener('click', planRoute);
                }
            }
            
            // 规划路线
            function planRoute() {
                // 清除之前的路线
                if (routeLine) {
                    map.removeOverlay(routeLine);
                }
                
                // 获取路线类型
                var routeType = document.querySelector('input[name="route-type"]:checked').value;
                
                // 显示加载提示
                var loadingTip = document.createElement('div');
                loadingTip.id = 'loading-tip';
                loadingTip.style.position = 'absolute';
                loadingTip.style.top = '50%';
                loadingTip.style.left = '50%';
                loadingTip.style.transform = 'translate(-50%, -50%)';
                loadingTip.style.padding = '10px 20px';
                loadingTip.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
                loadingTip.style.color = '#fff';
                loadingTip.style.borderRadius = '5px';
                loadingTip.style.zIndex = '2000';
                loadingTip.textContent = '正在规划路线，请稍候...';
                document.getElementById('map-container').appendChild(loadingTip);
                
                // 先尝试使用服务器端API
                console.log("尝试使用服务器端路线规划API...");
                fetch(`/api/route?startLat=${startPoint.lat}&startLng=${startPoint.lng}&endLat=${endPoint.lat}&endLng=${endPoint.lng}&mode=${routeType}`)
                    .then(response => response.json())
                    .then(data => {
                        // 移除加载提示
                        var loadingTip = document.getElementById('loading-tip');
                        if (loadingTip) {
                            loadingTip.parentNode.removeChild(loadingTip);
                        }
                        
                        if (data.status === 0 && data.result && data.result.routes && data.result.routes.length > 0) {
                            var route = data.result.routes[0];
                            
                            // 解析路线点
                            var points = [];
                            
                            // 驾车和步行路线
                            for (var i = 0; i < route.steps.length; i++) {
                                var path = route.steps[i].path;
                                for (var j = 0; j < path.length; j++) {
                                    points.push(new BMap.Point(path[j].lng, path[j].lat));
                                }
                            }
                            
                            // 创建折线
                            if (points.length >= 2) {
                                routeLine = new BMap.Polyline(points, {
                                    strokeColor: "#0000ff",
                                    strokeWeight: 5,
                                    strokeOpacity: 0.8
                                });
                                
                                // 添加到地图
                                map.addOverlay(routeLine);
                                
                                // 调整视图以包含整个路线
                                map.setViewport(points);
                                
                                // 显示路线信息
                                alert(`路线规划成功！\n总距离: ${route.distance}米\n预计用时: ${route.duration}秒`);
                            } else {
                                console.error('路线点数量不足，无法绘制路线');
                                useBaiduJsRouteAPI(routeType);
                            }
                        } else {
                            console.error('服务器端路线规划API返回错误:', data);
                            
                            // 获取详细错误信息
                            var errorMsg = '';
                            if (data.status) {
                                errorMsg = `错误代码: ${data.status}`;
                                if (data.message) {
                                    errorMsg += `, 错误信息: ${data.message}`;
                                }
                            } else {
                                errorMsg = 'API 服务被禁用或返回格式不正确';
                            }
                            
                            console.log("尝试使用百度地图JS API路线规划...");
                            useBaiduJsRouteAPI(routeType);
                        }
                    })
                    .catch(error => {
                        // 移除加载提示
                        var loadingTip = document.getElementById('loading-tip');
                        if (loadingTip) {
                            loadingTip.parentNode.removeChild(loadingTip);
                        }
                        
                        console.error('路线规划请求失败:', error);
                        
                        // 使用百度地图JS API作为备选
                        console.log("尝试使用百度地图JS API路线规划...");
                        useBaiduJsRouteAPI(routeType);
                    });
            }
            
            // 使用百度地图JS API进行路线规划
            function useBaiduJsRouteAPI(routeType) {
                var startPt = new BMap.Point(startPoint.lng, startPoint.lat);
                var endPt = new BMap.Point(endPoint.lng, endPoint.lat);
                
                // 清除之前的路线
                if (routeLine) {
                    map.removeOverlay(routeLine);
                }
                
                // 创建路线规划实例
                var routeSearch;
                var routeOptions = {
                    renderOptions: {
                        map: map,
                        autoViewport: true,
                        enableDragging: true
                    },
                    onSearchComplete: function(results) {
                        if (routeSearch.getStatus() == BMAP_STATUS_SUCCESS) {
                            // 路线规划成功
                            var plan = results.getPlan(0);
                            var duration = Math.round(plan.getDuration(false) / 60); // 分钟
                            var distance = plan.getDistance(false);  // 米
                            
                            alert(`路线规划成功！\n总距离: ${distance}米\n预计用时: ${duration}分钟`);
                        } else {
                            // 路线规划失败，显示错误信息
                            console.error('百度地图JS API路线规划失败:', routeSearch.getStatus());
                            var statusText = '';
                            switch(routeSearch.getStatus()) {
                                case BMAP_STATUS_UNKNOWN_LOCATION:
                                    statusText = '位置未知';
                                    break;
                                case BMAP_STATUS_UNKNOWN_ROUTE:
                                    statusText = '路线未知';
                                    break;
                                case BMAP_STATUS_INVALID_KEY:
                                    statusText = 'API密钥无效';
                                    break;
                                case BMAP_STATUS_INVALID_REQUEST:
                                    statusText = '请求无效';
                                    break;
                                case BMAP_STATUS_PERMISSION_DENIED:
                                    statusText = '没有权限';
                                    break;
                                case BMAP_STATUS_SERVICE_UNAVAILABLE:
                                    statusText = '服务不可用';
                                    break;
                                case BMAP_STATUS_TIMEOUT:
                                    statusText = '请求超时';
                                    break;
                                default:
                                    statusText = '未知错误';
                            }
                            alert(`路线规划失败: ${statusText}\n请稍后重试或选择其他出行方式。`);
                        }
                    }
                };
                
                try {
                    if (routeType === 'driving') {
                        routeSearch = new BMap.DrivingRoute(map, routeOptions);
                    } else if (routeType === 'walking') {
                        routeSearch = new BMap.WalkingRoute(map, routeOptions);
                    } else {
                        // 默认使用驾车
                        routeSearch = new BMap.DrivingRoute(map, routeOptions);
                    }
                    
                    // 执行路线规划
                    routeSearch.search(startPt, endPt);
                } catch (error) {
                    console.error('使用百度地图JS API路线规划时出错:', error);
                    alert('路线规划出错，请稍后重试。');
                }
            }
            
            // 显示内部地点
            function showInternalPlaces(placeId) {
                fetch(`/api/places/${placeId}/internal`)
                    .then(response => response.json())
                    .then(internalPlaces => {
                        if (internalPlaces.length === 0) {
                            alert('该地点暂无内部地点数据');
                            return;
                        }
                        
                        // 清除地图上的所有覆盖物
                        map.clearOverlays();
                        
                        // 添加内部地点标记
                        internalPlaces.forEach(place => {
                            var point = new BMap.Point(place.longitude, place.latitude);
                            var marker = new BMap.Marker(point);
                            
                            // 修改内部地点标记点击事件，直接跳转而不是显示信息窗口
                            marker.addEventListener("click", function() {
                                goToSinglePlaceMap(place.id);
                            });
                            
                            map.addOverlay(marker);
                        });
                        
                        // 添加"返回"按钮
                        var backButton = document.createElement('button');
                        backButton.textContent = '返回主地图';
                        backButton.style.position = 'absolute';
                        backButton.style.bottom = '20px';
                        backButton.style.left = '20px';
                        backButton.style.padding = '10px';
                        backButton.style.zIndex = '1000';
                        backButton.onclick = function() {
                            map.clearOverlays();
                            document.body.removeChild(backButton);
                            loadPlaces();
                        };
                        
                        document.body.appendChild(backButton);
                        
                        // 调整视图
                        var points = internalPlaces.map(p => new BMap.Point(p.longitude, p.latitude));
                        map.setViewport(points);
                    })
                    .catch(error => {
                        console.error('获取内部地点失败:', error);
                        alert('获取内部地点数据失败，请稍后重试');
                    });
            }
            
            // 初始化筛选器事件
            function initFilterEvents() {
                var checkboxes = document.querySelectorAll('#place-types input[type="checkbox"]');
                checkboxes.forEach(checkbox => {
                    checkbox.addEventListener('change', filterPlaces);
                });
                
                // 全选/全不选逻辑
                var allCheckbox = document.querySelector('#place-types input[value="all"]');
                allCheckbox.addEventListener('change', function() {
                    var checked = this.checked;
                    checkboxes.forEach(box => {
                        if (box.value !== 'all') {
                            box.checked = checked;
                            box.disabled = checked;
                        }
                    });
                    filterPlaces();
                });
            }
            
            // 地点筛选
            function filterPlaces() {
                var allCheckbox = document.querySelector('#place-types input[value="all"]');
                var typeCheckboxes = Array.from(document.querySelectorAll('#place-types input[type="checkbox"]:not([value="all"])'));
                
                // 如果"全部"被选中
                if (allCheckbox.checked) {
                    markers.forEach(marker => marker.show());
                    placeOutlines.forEach(outline => outline.show());
                    return;
                }
                
                // 获取选中的类型
                var selectedTypes = typeCheckboxes
                    .filter(checkbox => checkbox.checked)
                    .map(checkbox => checkbox.value);
                
                // 筛选标记
                markers.forEach(marker => {
                    if (selectedTypes.includes(marker.placeType)) {
                        marker.show();
                    } else {
                        marker.hide();
                    }
                });
                
                // 筛选轮廓
                placeOutlines.forEach(outline => {
                    if (selectedTypes.includes(outline.placeType)) {
                        outline.show();
                    } else {
                        outline.hide();
                    }
                });
            }
            
            // 搜索功能
            document.getElementById('search-box').addEventListener('keyup', function(e) {
                if (e.key === 'Enter') {
                    var keyword = this.value.trim();
                    if (keyword) {
                        searchPlaces(keyword);
                    }
                }
            });
            
            // 地点搜索功能
            function searchPlaces(keyword) {
                if (!keyword || keyword.trim() === '') {
                    alert('请输入搜索关键词');
                    return;
                }
                
                var sortBy = document.getElementById('search-sort').value;
                console.log('搜索地点:', keyword, '排序:', sortBy);
                document.getElementById('search-results').innerHTML = '<p>正在搜索...</p>';
                
                // 调用API搜索地点
                fetch(`/api/places/search?keyword=${encodeURIComponent(keyword)}&sortBy=${sortBy}`)
                    .then(response => response.json())
                    .then(places => {
                        var resultsContainer = document.getElementById('search-results');
                        
                        if (places.length === 0) {
                            resultsContainer.innerHTML = '<p>未找到匹配的地点</p>';
                            return;
                        }
                        
                        // 显示搜索结果
                        var html = '<ul style="list-style: none; padding: 0; margin: 0;">';
                        places.forEach(place => {
                            // 根据排序方式显示热度或评价
                            var scoreText = '';
                            if (sortBy === 'popularity') {
                                scoreText = `热度: ${place.popularity.toFixed(1)}`;
                            } else if (sortBy === 'rating') {
                                scoreText = `评价: ${place.rating.toFixed(1)}`;
                            }
                            
                            html += `<li style="padding: 5px; border-bottom: 1px solid #eee; cursor: pointer;" 
                                        onclick="goToPlace(${place.id}, ${place.latitude}, ${place.longitude}, '${place.name}')">
                                        <strong>${place.name}</strong> <small>(${place.type})</small>
                                        ${scoreText ? '<br><span>' + scoreText + '</span>' : ''}
                                    </li>`;
                        });
                        html += '</ul>';
                        
                        resultsContainer.innerHTML = html;
                    })
                    .catch(error => {
                        console.error('搜索失败:', error);
                        document.getElementById('search-results').innerHTML = '<p>搜索失败，请稍后重试</p>';
                    });
            }
            
            // 跳转到指定地点
            function goToPlace(id, lat, lng, name) {
                // 清空搜索结果
                document.getElementById('search-results').innerHTML = '';
                document.getElementById('search-box').value = '';
                
                // 直接跳转到单点地图页面，不显示信息窗口
                goToSinglePlaceMap(id);
            }
            
            // 页面加载完成后初始化
            window.onload = function() {
                // 显示北京市边界
                showBeijingBoundary();
                // 加载地点数据
                loadPlaces();
                // 加载推荐地点
                loadRecommendedPlaces();
                
                // 设置搜索框事件
                document.getElementById('search-box').addEventListener('keyup', function(e) {
                    if (e.key === 'Enter') {
                        searchPlaces(this.value);
                    }
                });
            };
            
            // 加载推荐地点
            function loadRecommendedPlaces() {
                console.log("开始执行loadRecommendedPlaces函数");
                // 先显示静态内容，确保有内容可见
                document.getElementById('recommended-places').innerHTML = '<p style="color:blue">正在加载推荐地点数据...</p>';

                try {
                    var sortBy = document.getElementById('recommend-sort').value;
                    var url = `/api/places/recommend/${sortBy}?limit=10`;
                    
                    console.log('加载推荐地点，排序方式:', sortBy, '请求URL:', url);
                    
                    fetch(url)
                        .then(response => {
                            console.log('推荐API响应状态:', response.status);
                            if(!response.ok) {
                                throw new Error('API响应错误: ' + response.status);
                            }
                            return response.json();
                        })
                        .then(places => {
                            console.log('获取到推荐地点:', places.length, '个', places);
                            var container = document.getElementById('recommended-places');
                            
                            if (places.length === 0) {
                                container.innerHTML = '<p>没有找到推荐地点</p>';
                                return;
                            }
                            
                            var html = '<ul style="list-style: none; padding: 0; margin: 0;">';
                            for (var i = 0; i < places.length; i++) {
                                var place = places[i];
                                var color = '#28a745'; // Default green
                                if (place.type === '学校') color = '#007bff'; // Blue for schools
                                
                                html += `
                                <li style="padding: 8px; margin-bottom: 5px; border-bottom: 1px solid #eee; cursor: pointer; background-color: #f9f9f9; border-left: 4px solid ${color};" onclick="goToPlace(${place.id}, ${place.latitude}, ${place.longitude}, '${place.name}')">
                                    <span style="display: inline-block; width: 20px; height: 20px; background-color: ${color}; color: white; border-radius: 50%; text-align: center; line-height: 20px; margin-right: 8px; font-weight: bold;">${i+1}</span>
                                    <strong>${place.name}</strong> <small>(${place.type})</small><br>
                                    <span><strong>${sortBy === 'popularity' ? '热度:' : '评价:'}</strong> ${sortBy === 'popularity' ? place.popularity.toFixed(1) : getRatingStars(place.rating)}</span>
                                </li>`;
                            }
                            html += '</ul>';
                            container.innerHTML = html;
                        })
                        .catch(error => {
                            console.error('获取推荐地点错误:', error);
                            document.getElementById('recommended-places').innerHTML = '<p style="color:red">加载推荐地点失败: ' + error.message + '</p>';
                        });
                } catch(e) {
                    console.error("loadRecommendedPlaces函数异常:", e);
                    document.getElementById('recommended-places').innerHTML = '<p style="color:red">加载推荐地点出错: ' + e.message + '</p>';
                }
            }
            
            // 为地点评分
            function ratePlace(placeId) {
                var ratingSelect = document.getElementById(`rate-${placeId}`);
                var rating = parseInt(ratingSelect.value);
                
                fetch(`/api/places/${placeId}/rate`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ rating: rating })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('评分成功！新的评分为: ' + data.new_rating.toFixed(1));
                        // 刷新推荐列表
                        loadRecommendedPlaces();
                    } else {
                        alert('评分失败: ' + (data.error || '未知错误'));
                    }
                })
                .catch(error => {
                    console.error('评分请求失败:', error);
                    alert('评分请求失败，请稍后重试');
                });
            }
        }
    </script>
</body>
</html>
